<template>
  <div class="params">
       <el-breadcrumb separator="/">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>商品管理</el-breadcrumb-item>
            <el-breadcrumb-item>参数列表</el-breadcrumb-item>
      </el-breadcrumb>
       <el-row>
           <el-col>
               <el-alert
                     closable
                    title="注意：只允许为第三级分类设置相关参数"
                    type="warning"
                    show-icon>
               </el-alert>
           </el-col>
       </el-row>
       <!-- 选择商品分类联级选择器 -->
       <el-row class="params_opt">
           <el-col>
               <span>选择商品分类: </span>
               <el-cascader
                    expand-trigger="hover"
                    :options="cateList"
                    :props="props"
                    v-model="defaultKeys"
                    @change="cateChange"
                    >
                </el-cascader>
           </el-col>
       </el-row>
       <!-- tabs选项卡 -->
       <el-tabs v-model="activeName" @tab-click="handleClick">
            <el-tab-pane label="动态参数" name="many">
                <el-button type="primary" size="mini" :disabled="defaultKeys.length !== 3"
                @click="dialogVisible = true">添加参数</el-button>
                <!-- 动态参数表格 -->
                <el-table :data="manyList" border>
                    <el-table-column type="expand">
                      <template slot-scope="scope">
                           <el-tag
                            v-for="(tag,i) in scope.row.attr_vals"
                            :key="tag.name"
                            :closable="tagClose"
                            @close="handeleClose(i,scope.row)"
                           >
                            {{tag}}

                          </el-tag>
                            <el-input
                            class="input-new-tag"
                            v-if="scope.row.inputVisible"
                            v-model="scope.row.inputValue"
                            ref="saveTagInput"
                            size="small"
                            @keyup.enter.native="handleInputConfirm(scope.row)"
                            @blur="handleInputConfirm(scope.row)"
                          >
                          </el-input>
                          <el-button v-else class="button-new-tag" size="small"
                           @click="showInput(scope.row)">+ New Tag</el-button>
                      </template>
                    </el-table-column>
                   <el-table-column type="index" label="#"></el-table-column>
                   <el-table-column prop="attr_name" label="动态参数"></el-table-column>
                   <el-table-column  label="操作">
                      <template >
                          <el-button type="primary" size="mini">编辑</el-button>
                          <el-button type="danger" size="mini">删除</el-button>

                      </template>
                   </el-table-column>
                </el-table>
            </el-tab-pane>
            <el-tab-pane label="静态属性" name="only">
                <el-button type="primary" size="mini" :disabled="defaultKeys.length !== 3"
                @click="dialogVisible = true">添加属性</el-button>
                 <!-- 静态属性表格 -->
                 <el-table :data="onlyList" border>
                   <el-table-column type="expand">
                          <template slot-scope="scope">
                           <el-tag
                            v-for="(tag,i) in scope.row.attr_vals"
                            :key="tag.name"
                            closable
                            @close="handeleClose(i,scope.row)"
                           >
                            {{tag}}

                          </el-tag>
                          <el-input
                            class="input-new-tag"
                            v-if="scope.row.inputVisible"
                            v-model="scope.row.inputValue"
                            ref="saveTagInput"
                            size="small"
                            @keyup.enter.native="handleInputConfirm(scope.row)"
                            @blur="handleInputConfirm(scope.row)"
                          >
                          </el-input>
                          <el-button v-else class="button-new-tag" size="small"
                           @click="showInput(scope.row)">+ New Tag</el-button>
                      </template>
                   </el-table-column>
                   <el-table-column type="index" label="#"></el-table-column>
                   <el-table-column prop="attr_name" label="静态属性"></el-table-column>
                   <el-table-column  label="操作">
                      <template slot-scope="scope">
                          <el-button type="primary" size="mini">编辑</el-button>
                          <el-button type="danger" size="mini">删除</el-button>
                          {{scope.row}}
                      </template>
                   </el-table-column>
                </el-table>
            </el-tab-pane>
       </el-tabs>
       <!-- 对话框 -->
         <el-dialog
              :title="'添加'+titleText"
              :visible.sync="dialogVisible"
              width="50%"
              @close="beforClose"
              >
               <el-form :model="addForm" :rules="addRules" ref="ruleRef" label-width="100px" >
                  <el-form-item :label="titleText" prop="attr_name">
                    <el-input v-model="addForm.attr_name"></el-input>
                  </el-form-item>
               </el-form>
              <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="addSubmit">确 定</el-button>
              </span>
        </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
      // 级联选择器数组
      cateList: [],
      // 级联选择器配置,
      props: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      // 联级选择器默认选中的参数
      defaultKeys: [],
      // tab绑定的数据
      activeName: 'many',
      manyList: [],
      onlyList: [],
      dialogVisible: false, // 控制对话框显示与隐藏
      addForm: {
        attr_name: ''
      }, // 对话框表单数据对象
      addRules: {
        attr_name: [{ required: true, message: '请输入参数名称', trigger: 'blur' }]
      },
      tagClose: true

    }
  },
  async mounted () {
    const { data: res } = await this.$axios.get('categories')
    if (res.meta.status !== 200) {
      return this.$message.error('数据获取失败')
    }
    this.cateList = res.data
    console.log(this.cateList)
  },
  methods: {
    cateChange () {
      // 设置选择器只允许选择三级
      if (this.defaultKeys.length !== 3) {
        this.defaultKeys = []
        this.manyList = []
        this.onlyList = []
      }
      this.getParamsList()
    },

    // tab切换触发的函数
    handleClick (tab) {
      this.getParamsList()
    },
    async   getParamsList () {
      const { data: res } = await this.$axios.get(`categories/${this.cateId}/attributes`, { params: { sel: this.activeName } })
      if (res.meta.status !== 200) {
        return this.$message.error('参数获取失败')
      }

      res.data.forEach(item => {
        item.attr_vals = item.attr_vals.trim() ? item.attr_vals.split(' ') : []
        item.inputVisible = false
        item.inputValue = ''
      })
      if (this.activeName === 'many') {
        this.manyList = res.data
      } else {
        this.onlyList = res.data
      }
    },
    // 对话框关闭前事件
    beforClose () {
      this.$refs.ruleRef.resetFields()
    },
    // 点击确定提交表单
    addSubmit () {
      this.$refs.ruleRef.validate(async valid => {
        if (!valid) return this.$message.error('数据校验失败')
        const { data: res } = await this.$axios.post(`categories/${this.cateId}/attributes`, {
          attr_name: this.addForm.attr_name,
          attr_sel: this.activeName
        })
        if (res.meta.status !== 201) {
          return this.$message.error('添加失败')
        }
        this.$message.success('添加成功')
        this.getParamsList()
      })
      this.dialogVisible = false
    },
    // 关闭Tag的函数
    async  handeleClose (i, objVal) {
      objVal.attr_vals.splice(i, 1)
      const { data: res } = await this.$axios.delete(`categories/${this.cateId}/attributes/${objVal.attr_id}`)
      if (res.meta.status !== 200) {
        return this.$message.error('删除失败')
      }
      this.$message.success('删除成功')
    },
    async handleInputConfirm (item) {
      if (item.inputValue.trim().length === 0) {
        item.inputValue = ''
        item.inputVisible = false
        return
      }
      item.attr_vals.push(item.inputValue)
      item.inputValue = ''
      const { data: res } = await this.$axios.put(`categories/${this.cateId}/attributes/${item.attr_id}`, {
        attr_name: item.attr_name,
        attr_sel: item.attr_sel,
        attr_vals: item.attr_vals.join(' ')
      })
      if (res.meta.status !== 200) {
        return this.$message.error('更新失败')
      }
      this.$message.success('更新成功')

      item.inputVisible = false
    },
    showInput (item) {
      item.inputVisible = true
      this.$nextTick(() => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    }
  },
  computed: {
    cateId () {
      if (this.defaultKeys.length === 3) {
        return this.defaultKeys[2]
      } else {
        return null
      }
    },
    // 对话框标题
    titleText () {
      if (this.activeName === 'many') {
        return '动态属性'
      }
      return '静态参数'
    }
  }
}
</script>

<style scoped>
.params_opt {
    margin: 15px 0;
}
.el-tag {
  margin-right: 15px;
}
.input-new-tag {
  width: 120px;
}
</style>
